package com.platform.api;

import com.alibaba.fastjson.JSONObject;
import com.platform.entity.QueryTrackResp;
import com.platform.util.ApiBaseAction;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("api/logistics")
public class ApiLogisticsController extends ApiBaseAction{
    private Logger logger = LoggerFactory.getLogger(ApiLogisticsController.class);


    @Value("${express.key}")
    private String expressKey="";
    @Value("${express.customer}")
    private String expressCustomer="";


    /**
     * 获取用户收藏
     */

    @RequestMapping("/info")
    public Object list(@RequestBody Map<String,Object> params) {
        logger.info("物流参数:params{}",params);
        String com = params.get("com").toString();
        String num = params.get("num").toString();
        if (StringUtils.isBlank(com)){
            return toResponsFail("物流公司编码不能为空");
        }
        if (StringUtils.isBlank(num)){
            return toResponsFail("物流单号不能为空");
        }
        String param="{\"com\":\""+com+"\",\"num\":\""+num+"\",\"from\":\"\",\"phone\":\"\",\"to\":\"\",\"resultv2\":0,\"show\":\"0\",\"order\":\"desc\"}";
        Map<String, String> map = new HashMap<String, String>();
//        String param = "{\"com\":\"" + com + "\",\"num\":\"" + num + "\"}";
        String str= DigestUtils.md5Hex(param+expressKey+expressCustomer).toUpperCase();
        map.put("customer", expressCustomer);
        map.put("sign", str);
        map.put("param",param);
        String result=this.post(map);
        QueryTrackResp queryTrackResp = JSONObject.parseObject(result,QueryTrackResp.class);
        return toResponsSuccess(queryTrackResp);
    }



    public String post(Map<String, String> params) {

        StringBuilder response = new StringBuilder("");

        BufferedReader reader = null;

        try {

            StringBuilder builder = new StringBuilder();

            for (Map.Entry<String, String> param : params.entrySet()) {

                if (builder.length() > 0) {

                    builder.append('&');

                }

                builder.append(URLEncoder.encode(param.getKey(), "UTF-8"));

                builder.append('=');

                builder.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));

            }

            byte[] bytes = builder.toString().getBytes("UTF-8");

            URL url = new URL("https://poll.kuaidi100.com/poll/query.do");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setConnectTimeout(3000);

            conn.setReadTimeout(3000);

            conn.setRequestMethod("POST");

            conn.setRequestProperty("accept", "*/*");

            conn.setRequestProperty("connection", "Keep-Alive");

            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));

            conn.setDoOutput(true);

            conn.getOutputStream().write(bytes);

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

            String line = "";

            while ((line = reader.readLine()) != null) {

                response.append(line);

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            try {

                if (null != reader) {

                    reader.close();

                }

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        return response.toString();

    }

}